package com.wx.push.subscription.push.utils;

import com.alibaba.fastjson.JSONObject;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author 01424605
 * @create 2022-08-22 13:48
 */
public class MsgApiUtil {
    public static String getAMessage(String url,String key, String httpArg) {
        String res = null;
        key = "3d6f98e93c56503d2e40d3ca8eb3972c";
        String request = request(url + "?key="+ key, httpArg);
        JSONObject jsonObject = JSONObject.parseObject(request);
        if (jsonObject.getIntValue("code") == 200) {
            res = jsonObject.getJSONArray("newslist").getJSONObject(0).getString("content");
        }
        return res;
    }

    //java环境中文传值时，需特别注意字符编码问题
    String httpUrl = "http://api.tianapi.com/caihongpi/index?key=你的APIKEY";
    String jsonResult = request(httpUrl,"");
//    System.out.println(jsonResult);

    /**
     * @param httpUrl  请求接口
     * @param httpArg  参数
     * @return 返回结果
     */
    public static String request(String httpUrl, String httpArg) {
        BufferedReader reader = null;
        String result = null;
        StringBuffer sbf = new StringBuffer();
        if(!StringUtils.isEmpty(httpArg)) httpUrl = httpUrl + httpArg;

        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setRequestMethod("GET");
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            reader.close();
            result = sbf.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
